<template>
  <div class="study-detail-v5">
    <div class="controls">
      <el-select v-model="seriesInstanceUid" placeholder="请选择序列实例" style="width: 320px; margin-right: 10px;">
        <el-option v-for="s in seriesInstanceUidOptions" :key="s.seriseId" :label="s.seriseId" :value="s.seriseId" />
      </el-select>
      <el-button type="primary" @click="loadSeries">加载影像</el-button>
    </div>
    <DualViewportSeriesPanel :image-ids="imageIds" mode="qiniu" />
  </div>
  
</template>

<script setup>
import { useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'
import DualViewportSeriesPanel from '@/components/dualViewportSeriesPanel/DualViewportSeriesPanel.vue'
import { getSeriseAllList } from '@/api/pacs/serise/serise'
import { getSeriesImages } from '@/api/pacs/dicom/dicom.js'
import { createQiniuImageIds } from '@/utils/dicom/dicom'
import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader'
import { imageLoader, metaData } from '@cornerstonejs/core'
import { DicomDataService } from '@/api/pacs/dicom/dicomService.js'

const route = useRoute()
const studyId = ref(null)
const seriesInstanceUid = ref('')
const seriesInstanceUidOptions = ref([])
const imageIds = ref([])

// 为 qiniu:imageId 注册元数据转发 provider：qiniu:http... -> wadouri:http...
// 本地元数据缓存（以 wadouri:blobURL 为键），同时维护 qiniu->wadouri 映射
let qiniuMetaProviderRegistered = false
const localMetaCache = {
  imagePixelModule: {},
  voiLutModule: {},
  generalSeriesModule: {},
  imagePlaneModule: {},
  generalImageModule: {},
  sopCommonModule: {},
  transferSyntax: {},
}
const wadouriByQiniu = new Map()

function addLocalMeta(type, imageId, data) {
  if (!data) return
  const bucket = localMetaCache[type]
  if (bucket) bucket[imageId] = data
}

function registerQiniuMetaProvider() {
  if (qiniuMetaProviderRegistered) return
  const priority = 1500
  const provider = (type, imageId) => {
    if (typeof imageId !== 'string') return undefined
    // 直接命中 wadouri:blobURL 的本地缓存
    if (imageId.startsWith('wadouri:')) {
      const cached = localMetaCache[type]?.[imageId]
      if (cached) return cached
    }
    // 支持 qiniu:ID -> wadouri:blobURL 的映射
    if (imageId.startsWith('qiniu:')) {
      const wadouriId = wadouriByQiniu.get(imageId)
      if (wadouriId) {
        const cached = localMetaCache[type]?.[wadouriId]
        if (cached) return cached
      }
    }
    return undefined
  }
  try {
    metaData.addProvider(provider, priority)
  } finally {
    qiniuMetaProviderRegistered = true
  }
}

function registerQiniuImageLoader() {
  // 仅注册一次
  try {
    // 检查是否已注册，判断：注册一个同名loader会覆盖，这里直接注册就行
    try { imageLoader.unregisterImageLoader('qiniu') } catch (e) {}
    // 先注册元数据 provider，保证 Volume 构建能获取到元数据
    registerQiniuMetaProvider()
    imageLoader.registerImageLoader('qiniu', (imageId) => {
      const promise = (async () => {
        const url = imageId.replace('qiniu:', '').split('?')[0]
        const ds = new DicomDataService()
        const arrayBuffer = await ds.fetchDicomFromQiniu(url)
        const blob = new Blob([arrayBuffer], { type: 'application/dicom' })
        const blobUrl = URL.createObjectURL(blob)
        const wadouriImageId = `wadouri:${blobUrl}`

        // 解析数据集并填充本地元数据缓存（以 wadouri:blobURL 为键）
        try {
          const dataSet = cornerstoneDICOMImageLoader.external.dicomParser.parseDicom(new Uint8Array(arrayBuffer))
          const types = [
            'imagePixelModule',
            'voiLutModule',
            'generalSeriesModule',
            'imagePlaneModule',
            'generalImageModule',
            'sopCommonModule',
            'transferSyntax',
          ]
          types.forEach((t) => {
            try {
              const data = cornerstoneDICOMImageLoader.wadouri.metadataForDataset(t, wadouriImageId, dataSet)
              if (data) addLocalMeta(t, wadouriImageId, data)
            } catch (e) {
              /* swallow */
            }
          })
          // 建立映射，便于 qiniu:imageId 查询命中 wadouri:blobURL 缓存
          wadouriByQiniu.set(imageId, wadouriImageId)
        } catch (e) {
          // 解析失败时不阻塞图像加载
        }

        const imageLoadObject = cornerstoneDICOMImageLoader.wadouri.loadImage(wadouriImageId)
        const image = await imageLoadObject.promise
        // 不立即 revoke，避免后续访问像素或相关资源失败；可在卸载时清理
        return image
      })()
      return {
        promise,
        cancelFn: () => { },
      }
    })
  } catch (e) {
    // 忽略重复注册错误
  }
}

async function fetchSeriesList() {
  const res = await getSeriseAllList({ studyId: studyId.value })
  console.log('[V5] fetchSeriesList resp:', res)
  seriesInstanceUidOptions.value = res.data || []
  if (!seriesInstanceUid.value && seriesInstanceUidOptions.value.length > 0) {
    seriesInstanceUid.value = seriesInstanceUidOptions.value[0].seriseId
    console.log('[V5] default seriesInstanceUid:', seriesInstanceUid.value)
  }
}

async function loadSeries() {
  if (!studyId.value || !seriesInstanceUid.value) return
  const series = await getSeriesImages(studyId.value, seriesInstanceUid.value)
  console.log('[V5] getSeriesImages resp:', series)
  const tempImageIds = series.data?.images || []
  console.log('[V5] raw images from backend:', tempImageIds)
  registerQiniuImageLoader()
  imageIds.value = createQiniuImageIds(tempImageIds)
  console.log('[V5] imageIds after wrapping:', imageIds.value)
}

onMounted(async () => {
  studyId.value = route.query.studyId
  console.log('[V5] route.query:', route.query)
  await fetchSeriesList()
  await loadSeries() // 自动加载第一个序列
})
</script>

<style scoped>
.study-detail-v5 { padding: 8px; }
.controls { margin-bottom: 8px; }
</style>